/**
 * @name: findSiblingIds
 * @description: 获取传入id的兄弟节点
 * @param {Array} list //树形机构数据
 * @param {String} id //需要查找的id
 * @return {Array} //返回兄弟节点
 */
function findSiblingIds(list, id) {
  let node;
  for (let i in list) {
    if (list[i].id === id) {
      return list.filter((v) => v.id !== id);
    }
    if (list[i].children?.length > 0) {
      node = findSiblingIds(list[i].children, id);
      if (node) return node.filter((v) => v.id !== id);
    }
  }
  return node;
}

function addStationName(list) {
  list.forEach((item) => {
    if (item.level == 1) {
      item.label = item.orgName;
      item.id = item.orgId;
    }
    if (item.level == 2) {
      item.label = item.stationName;
      item.id = item.stationId;
    }
    if (item.level == 3) {
      item.label = item.unitsName;
      item.id = item.unitsId;
    }

    if (item.children) {
      addStationName(item.children);
    }
  });
  return list;
}

// 传入一个id获取它父级的id
function getAllParentNodes(list, id) {
  if (list.length === 0 || !list) return [];
  let node;

  for (let i in list) {
    if (list[i].id === id) {
      return [list[i]].filter((v) => v.id !== id);
    }
    if (list[i].children?.length > 0) {
      node = getAllParentNodes(list[i].children, id);
      if (node) return node.concat(list[i]).filter((v) => v.id !== id);
    }
  }
  return node;
}

import { Message } from "element-ui";
import {
  queryStationFileList,
  queryStationPassRate,
  insertOrUpdateStationInfoFile,
  insertStationInfoFile,
  updateStationInfoFile,
  getPdf,
  downloadStationTestInfo,
  deleteEnergyStation,
  deleteStationFile,
  queryStationTestNumber,
  insertOrUpdateStationInfoFileReport,
} from "@/api/windPower.js";
import {
  adjustRegulationList,
  regulationOrgList,
  stationTypeList,
  voltageLevelList,
  queryUnitsNameList,
  queryStationNameList,
  queryOfExperimentalresults,
  updateStationFileWarn,
} from "@/api/dict.js";
import TestResultQueryEdit from "@/views/testResultQuery/testResultQueryEdit/testResultQueryEdit.vue";
//引入VueOfficePdf组件
import * as XLSX from "xlsx";
// 导出
import { exportFn } from "@/utils/exportTable.js";

export default {
  components: { TestResultQueryEdit },
  name: "LabProjectIndex",
  data() {
    let yesOrNoList = {
      0: "否",
      1: "是",
    };

    return {
      queryStationFileList,
      queryStationNameList,
      queryUnitsNameList,
      queryStationPassRate,
      // getWindPowerList,
      formData: new FormData(),
      key: 1,
      excelData: [],
      columns: [],
      pdf: "", //设置文档地址
      getFrom: {}, //每行的数据
      dispatchList: [], //调度
      stationTypeLists: [], //类型
      adjustRegulationLists: [], //上下调投入分类下拉框的数据
      voltageLevelLists: [], //电压等级下拉框的数据
      addDialogVisibleTitle: "新增",
      id: 0,
      dataTree: [],
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
      isTestPassedList: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],

      defaultProps: {
        children: "children",
        label: "label",
      },
      queryDetailParam: {
        regulationOrgIds: [],
        stationIds: [],
        fileSort: "02",
        testDate: "",
        testNumber: "",
        isAudited: 1,
        isTestPassed: "",
        // regulationOrgId: "",
        // voltageLevelCode: "",
        // stationName: "",
        // ownersName: "",
        // isProduction: null,
        // capStart: "",
        // capEnd: "",
        // productionTime: "",
        // isRegulation: null,
        // adjustRegulationCode: "",
        // isResponse: null,
        // stationType: "7",
        // powerStart: "",
        // powerEnd: "",
        // speedStart: "",
        // speedEnd: "",
        // powerDurationStart: "",
        // powerDurationEnd: "",
        // isYes: [
        //   {
        //     label: "是",
        //     value: 1,
        //   },
        //   {
        //     label: "否",
        //     value: 0,
        //   },
        // ],
      },
      operate: "add",
      testNumberList: [], //测试序号
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
      headList: [
        {
          name: "所属调度",
          value: "regulationOrgName",
          noSort: true,
        },
        // { name: '类型', value: 'stationTypeName', noSort: true },
        {
          // name: '场站名称',
          name: "电厂名称",
          value: "stationName",
          noSort: true,
        },
        // {
        //   name: '单机容量',
        //   value: 'singleMachineCap',
        //   noSort: true,
        //   formatter: (row) => (row.singleMachineCap ? `${row.singleMachineCap}MW` : ''),
        // },
        // { name: '机组编号', value: 'unitsNumber', noSort: true },
        { name: "产权单位", value: "ownersName", noSort: true },

        {
          name: "上调/下调是否投入",
          value: "adjustRegulationName",
          noSort: true,
        },
        {
          name: "是否具备惯量响应",
          value: "isResponse",
          noSort: true,
          formatter: (row) =>
            yesOrNoList[row.isResponse] ? yesOrNoList[row.isResponse] : "",
          // formatter: (row) => (row.isResponse == 1 ? "是" : "否"),
        },
        // { name: '试验单位', value: 'testingUnitName', noSort: true },
        {
          name: "死区",
          value: "deadZone",
          noSort: true,
          formatter: (row) => (row.deadZone ? `±${row.deadZone}Hz` : ""),
        },
        {
          name: "调差系数",
          value: "adjustRatio",
          noSort: false,
          formatter: (row) => (row.adjustRatio ? `${row.adjustRatio}%` : ""),
        },
        {
          name: "启动功率门槛",
          value: "startingPowerThreshold",
          noSort: true,
          formatter: (row) =>
            row.startingPowerThreshold ? `${row.startingPowerThreshold}MW` : "",
        },
        {
          name: "下调限幅",
          value: "lowerLimit",
          noSort: true,
          formatter: (row) => (row.lowerLimit ? `${row.lowerLimit}MW` : ""),
        },
        {
          name: "上调限幅",
          value: "upLimit",
          noSort: true,
          formatter: (row) => (row.upLimit ? `${row.upLimit}MW` : ""),
        },
        {
          name: "启动时间",
          value: "startTime",
          noSort: true,
          formatter: (row) => (row.startTime ? `≤${row.startTime}s` : ""),
        },
        {
          name: "响应时间",
          value: "responseTime",
          noSort: true,
          formatter: (row) => (row.responseTime ? `≤${row.responseTime}s` : ""),
        },
        {
          name: "调节时间",
          value: "adjustTime",
          noSort: true,
          formatter: (row) => (row.adjustTime ? `≤${row.adjustTime}s` : ""),
        },
        {
          name: "功率调节偏差",
          value: "powerAdjustDeviation",
          noSort: true,
          formatter: (row) =>
            row.powerAdjustDeviation ? `${row.powerAdjustDeviation}MW` : "",
        },

        // {
        //   // name: '一次调频实验方案',
        //   name: '一次调频试验报告',
        //   value: 'regulationTestPlan',
        //   order: 'regulationTestPlanId',
        //   noSort: true,
        //   type: 'linkPreview',
        //   clickPreview: this.doPreview,
        //   clickDownload: this.doDownload,
        // },

        {
          // name: '一次调频实验方案',
          name: "快速频率响应试验结果",
          // value: "stationFileName",
          order: "fileId",
          noSort: true,
          type: "linkPreview",
          // type1:'upload',
          // clickPreview: this.doPreview,
          clickPreview: this.previewClick,
          clickDownload: this.doDownload,
          //clickUpload:this.doUpload
        },
        {
          // name: '实验方案上传时间',
          name: "上传时间",
          value: "uploadTime",
          noSort: false,
          formatter: (row) =>
            row.uploadTime ? row.uploadTime.replace("T", " ") : "",
        },
        {
          name: "审核通过",
          value: "isAudited",
          noSort: true,
          // fontColor: true,
          formatter: (row) =>
            yesOrNoList[row.isAudited] ? yesOrNoList[row.isAudited] : "",
        },
        {
          name: "审核时间",
          value: "auditedTime",
          noSort: false,
          formatter: (row) =>
            row.auditedTime ? row.auditedTime.replace("T", " ") : "",
        },

        { name: "测试日期", value: "testDate", noSort: true },

        { name: "测试序号", value: "testNumber", noSort: true },

        {
          name: "测试合格",
          value: "isTestPassed",
          noSort: true,
          // fontColor: true,
          formatter: (row) =>
            yesOrNoList[row.isTestPassed] ? yesOrNoList[row.isTestPassed] : "",
        },

        {
          name: "主动测试结果",
          value: "result",
          order: "stationId",
          noSort: true,
          type: "check",
          clickCheck: this.doCheck,
        },

        {
          name: "操作",
          value: "result",
          noSort: true,
          type: "addDlePreview",
          clickCopy: this.copyWindPower,
          clickEdit: this.editWindPower,
          clickDelete: this.deleteWindPower,
          // clickCheck: this.doCheck,
        },
      ],
      headList_1: [
        {
          name: "所属调度",
          value: "regulationOrgName",
          noSort: true,
        },
        // { name: '类型', value: 'stationTypeName', noSort: true },
        {
          // name: '场站名称',
          name: "电厂名称",
          value: "stationName",
          noSort: true,
        },
        // {
        //   name: '单机容量',
        //   value: 'singleMachineCap',
        //   noSort: true,
        //   formatter: (row) => (row.singleMachineCap ? `${row.singleMachineCap}MW` : ''),
        // },
        // { name: '机组编号', value: 'unitsNumber', noSort: true },
        { name: "产权单位", value: "ownersName", noSort: true },
        {
          name: "主动测试次数",
          value: "activeTestNum",
          noSort: true,
        },
        {
          name: "合格次数",
          value: "qualifiedNum",
          noSort: true,
        },
        {
          name: "合格率/%",
          value: "qualifiedRatio",
          noSort: true,
        },
      ],
      // 新增弹框显示
      dialogFormVisible: false,
      formLabelWidth: "80px",
      // 预览弹框
      dialogPreVisible: false,
      paramData: [],
      checkList: [],
      queryParamStationId: "",
    };
  },

  mounted() {},
  created() {
    this.regulationOrgList();
    this.stationTypeList();
    this.adjustRegulationList();
    this.voltageLevelList();
    this.getTreeData();
    this.getNowTime();
    this.queryStationTestNumber();
  },
  methods: {
    getNowTime() {
      // 获取当前日期
      var date = new Date();
      // 获取当前月份
      var nowMonth = date.getMonth() + 1;
      // 获取当前是几号
      var strDate = date.getDate();
      // 添加分隔符“-”
      var seperator = "-";
      // 对月份进行处理，1-9月在前面添加一个“0”
      if (nowMonth >= 1 && nowMonth <= 9) {
        nowMonth = "0" + nowMonth;
      }
      // 对月份进行处理，1-9号在前面添加一个“0”
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      // 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
      this.queryDetailParam.testDate =
        date.getFullYear() + seperator + nowMonth + seperator + strDate;
    },

    // 获取渲染树的数据
    getTreeData(data) {
      return;
      queryOfExperimentalresults(data).then((res) => {
        // let dataTree = []
        // addStationName(res.data)
        this.dataTree = addStationName(res.data);
        this.$nextTick(function () {
          if (data == undefined) {
            this.$refs.equipmentTree.setCheckedKeys([]);
            this.checkList = [];
            this.queryParamStationId = "";
          } else {
            this.$refs.equipmentTree.setCheckedKeys([data.stationId]);
            let list = [data.stationId];
            this.queryParamStationId = data.stationId;
            console.log(list);
            this.checkList = list;

            let params = {
              regulationOrgIds: [],
              stationIds: list,
              fileSort: "01",
            };
            this.queryDetailParam = params;
            params.stationIds.forEach((e, i) => {
              // console.log(params.regulationOrgIds.includes(getAllParentNodes(this.dataTree,e)[0].id))
              if (
                params.regulationOrgIds.includes(
                  getAllParentNodes(this.dataTree, e)[0].id
                )
              ) {
                // 找到这个元素删掉他
                this.queryDetailParam.stationIds =
                  this.queryDetailParam.stationIds.filter((d) => d !== e);
              }
            });
            this.$nextTick(() => {
              this.$refs.windPowerTable.getDataInit();
            });
          }
        });
      });
    },
    // 下拉框change事件
    inputChange(val) {
      console.log(val, "搜索下拉框val");
      console.log(this.$refs.equipmentTree.queryInputListCopy, "搜索下拉框val");
      let param = {
        stationId: val,
      };

      this.getTreeData(param);
    },
    // 点击树的勾选框
    handleCheck(checkedKeys, e) {
      // console.log(checkedKeys, e, "checkedKeys");
      // let nodeList = this.$refs.equipmentTree.getCheckedKeys();

      // this.$nextTick(() => {

      if (this.queryParamStationId !== "") {
        let params = {
          regulationOrgIds: [],
          stationIds: [],
          fileSort: "02",
        };
        if (e.checkedKeys[1]) {
          params.stationIds.push(e.checkedKeys[1]);
        }
        this.queryDetailParam = params;
      } else {
        let nodeList = this.$refs.equipmentTree.getCheckedNodes();
        let params = {
          regulationOrgIds: [],
          stationIds: [],
          fileSort: "02",
        };
        nodeList
          .filter((e) => e.level !== "3")
          .forEach((item) => {
            if (item.level === "1") {
              params.regulationOrgIds.push(item.id);
            }
            if (item.level === "2") {
              params.stationIds.push(item.id);
            }
          });
        this.queryDetailParam = params;
        params.stationIds.forEach((e, i) => {
          if (
            params.regulationOrgIds.includes(
              getAllParentNodes(this.dataTree, e)[0].id
            )
          ) {
            // 找到这个元素删掉他
            this.queryDetailParam.stationIds =
              this.queryDetailParam.stationIds.filter((d) => d !== e);
          }
        });
      }

      this.$nextTick(() => {
        this.$refs.windPowerTable.getDataInit();
        this.$refs.windPowerTable_1.getDataInit();
      });

      // });
    },
    // 处理三级节点之间勾选联动
    checkChange(row, col, check) {
      console.log(this.dataTree, "this.dataTree");
      if (row.level == "3") {
        // console.log(row, col, check, "row, col");
        let checkedKeys = findSiblingIds(this.dataTree, row.id);
        // console.log(checkedKeys,'checkedKeyscheckedKeys')
        checkedKeys.forEach((item) => {
          this.$refs.equipmentTree.setChecked(item.id, col);
        });
      }
    },

    // 总调下拉框的数据
    async regulationOrgList() {
      await regulationOrgList().then((res) => {
        if (res.code === "000000") {
          this.dispatchList = res.data;
        }
      });
    },

    // 上下调投入分类下拉框的数据
    async adjustRegulationList() {
      await adjustRegulationList().then((res) => {
        if (res.code === "000000") {
          this.adjustRegulationLists = res.data;
        }
      });
    },
    // 场站类型下拉框的数据
    async stationTypeList() {
      await stationTypeList().then((res) => {
        if (res.code === "000000") {
          this.stationTypeLists = res.data;
        }
      });
    },
    // 电压等级下拉框的数据
    async voltageLevelList() {
      await voltageLevelList().then((res) => {
        if (res.code === "000000") {
          this.voltageLevelLists = res.data;
        }
      });
    },

    // 测试日期
    testDateChange(val) {
      if (val) {
        this.queryStationTestNumber();
      }
    },

    // 测试序号下拉
    async queryStationTestNumber() {
      await queryStationTestNumber(this.queryDetailParam).then((res) => {
        if (res.code === "000000") {
          this.testNumberList = res.data;
        }
      });
    },
    // 新增弹框
    addWindPower() {
      this.id++;
      // this.operate === "add";
      this.$set(this, "operate", "add");
      this.dialogFormVisible = true;
      this.addDialogVisibleTitle = "新增";
      this.getFrom = { regulationOrgId: "1", reportIsAudited: "" };
    },

    // 获取表格多行选中的数据
    // getMultipleSelection(row) {
    //   this.tableData = JSON.parse(JSON.stringify(row))
    //   this.tableData.forEach((element) => {
    //     console.log(element, 'element')
    //     this.getFrom = element
    //   })
    // },

    // 获取表格多行选中的数据  点击行选中
    getMultipleSelection2(row) {
      this.tableData = JSON.parse(JSON.stringify(row));
      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },

    getMultipleSelection() {
      this.tableData = JSON.parse(
        JSON.stringify(this.$refs.windPowerTable.multipleSelection)
      );
      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },

    // // 编辑
    // editWindPower(row) {
    //   // this.operate = "edit";
    //   this.$set(this, 'operate', 'edit')
    //   this.getMultipleSelection([row])
    //   // this.$refs.childRules.$refs.FuzzyQueryInput.value = row.stationName
    //   this.dialogFormVisible = true
    //   this.addDialogVisibleTitle = '编辑'
    //   // this.$nextTick(() => {
    //   //   this.$refs.childRules.$refs.FuzzyQueryInput.value = row.stationName;
    //   // });

    //   return true
    //   // if (this.tableData && this.tableData.length < 1) {
    //   //   Message.warning("请先勾选要编辑的数据");
    //   // } else if (this.tableData && this.tableData.length > 1) {
    //   //   Message.warning("编辑的时候只能选择一条数据,请重新选择");
    //   //   return false;
    //   // } else {
    //   //   this.addDialogVisibleTitle = "编辑";
    //   //   this.dialogFormVisible = true;
    //   //   return true;
    //   // }
    // },

    editWindPower(row) {
      console.log(row);
      if (row) {
        this.$set(this, "operate", "edit");
        this.getMultipleSelection2([row]);
        this.dialogFormVisible = true;
        this.addDialogVisibleTitle = "编辑";
        return true;
      } else {
        this.operate = "edit";
        this.getMultipleSelection();
        if (this.tableData && this.tableData.length < 1) {
          Message.warning("请先勾选要编辑的数据");
        } else if (this.tableData && this.tableData.length > 1) {
          Message.warning("编辑的时候只能选择一条数据,请重新选择");
          return false;
        } else {
          this.addDialogVisibleTitle = "编辑";
          this.dialogFormVisible = true;
          // this.$nextTick(()=>{
          // this.$refs.childRules.$refs.stationRefEdit.value=this.getFrom.stationName
          // })
          return true;
        }
      }
    },

    // 复制
    copyWindPower(row) {
      // this.operate = "copy";
      this.$set(this, "operate", "copy");
      // this.getMultipleSelection();
      this.getMultipleSelection([row]);

      if (this.tableData && this.tableData.length < 1) {
        Message.warning("请先勾选要复制的数据");
      } else if (this.tableData && this.tableData.length > 1) {
        Message.warning("复制的时候只能选择一条数据,请重新选择");
        return false;
      } else {
        this.addDialogVisibleTitle = "复制";
        // 复制的时候清空所有的文件上传
        this.getFrom.regulationReportForm = "";
        this.getFrom.regulationTestPlan = "";
        this.getFrom.regulationTestReport = "";
        this.getFrom.responsePlan = "";
        this.getFrom.responseReport = "";
        this.dialogFormVisible = true;
        return true;
      }
    },

    // 删除
    deleteWindPower(row) {
      if (row) {
        this.$confirm("是否确认删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 发送请求
          let params = [row.stationFileId];
          // 发送请求
          // deleteStationFile({stationFileId:row.stationFileId}).then((res) => {
          deleteStationFile(params).then((res) => {
            if (res.code === "000000") {
              Message.success("删除成功");
              this.$refs.windPowerTable.getDataInit();
            }
          });
        });
      } else {
        if (this.$refs.windPowerTable.multipleSelection.length === 0) {
          Message.warning("请选择要删除的数据");
          return;
        }
        // 确认删除嘛
        this.$confirm("是否确认删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 发送请求
          let ids = this.$refs.windPowerTable.multipleSelection.map(
            (item) => item.stationFileId
          );
          // let params = {
          //   stationFileId:row.stationFileId
          // }
          // 发送请求
          deleteStationFile(ids).then((res) => {
            if (res.code === "000000") {
              Message.success("删除成功");
              this.$refs.windPowerTable.getDataInit();
            }
          });
        });
      }
    },

    // 检索
    searchList() {
      this.$refs.windPowerTable.getDataInit();
    },
    // 重置
    resetSearchList() {
      for (let key in this.queryDetailParam) {
        this.queryDetailParam[key] = "";
      }
      this.queryDetailParam.stationType = "7";
      this.$refs.windPowerTable.getDataInit();
    },

    // 详情重置
    resetCon() {
      this.getFrom = {};
      if (this.$refs.childRules.$refs.owner) {
        this.$refs.childRules.$refs.owner.labels = "";
      }
      if (this.$refs.childRules.$refs.testingUnit) {
        this.$refs.childRules.$refs.testingUnit.labels = "";
      }
    },

    // 下载
    async doDownload(row, col, name) {
      let excelName = `${name}`;
      // const res = await getPdf(row[`${col}Id`]);
      const res = await getPdf(row.stationFileId);
      let fileType = "";
      if (row && row.stationFileName) {
        fileType = row.stationFileName.substring(
          row.stationFileName.lastIndexOf(".") + 1
        );
      }
      // if (
      //   res.fileType !== "pdf" &&
      //   res.fileType !== "xlsx" &&
      //   res.fileType !== "xls"
      // ) {
      //   this.$message.warning("只支持pdf与excel格式的文件下载");
      //   return;
      // }
      let typeList = {
        pdf: "application/pdf",
        xls: "application/vnd.ms-excel",
        xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        doc: "application/msword",
        docx: "application/msword",
      };
      const link = document.createElement("a");
      let blob = new Blob([res], {
        // type: typeList[res.fileType],
        type: typeList[fileType],
      });
      // xlsx的文件type

      link.style.display = "none";
      link.href = URL.createObjectURL(blob);
      link.download = excelName; //下载的文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // async downloadWin() {
    //   let excelName = '频率响应试验方案列表.xlsx'
    //   const res = await downloadStationTestInfo(this.queryDetailParam)
    //   const link = document.createElement('a')
    //   let blob = new Blob([res], {
    //     type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    //   })
    //   link.style.display = 'none'
    //   link.href = URL.createObjectURL(blob)
    //   link.download = excelName //下载的文件名
    //   document.body.appendChild(link)
    //   link.click()
    //   document.body.removeChild(link)
    // },

    async downloadWin() {
      exportFn(
        "频率响应试验结果列表.xlsx",
        downloadStationTestInfo,
        this.queryDetailParam
      );
    },

    //  导出
    exportExcel() {
      this.downloadWin();
    },

    // 预览弹窗
    openMethods() {
      this.doPreview(this.row);
    },

    // 预览点击事件
    previewClick(row) {
      this.row = row;
      this.dialogPreVisible = true;
      this.key++;
    },

    // 预览
    async doPreview(row, col) {
      //const res = await getPdf(row[`${col}Id`]);
      const doc = require("docx-preview");
      const res = await getPdf(row.stationFileId);
      let fileType = "";
      if (row && row.stationFileName) {
        fileType = row.stationFileName.substring(
          row.stationFileName.indexOf(".") + 1
        );
      }
      // if (
      //   res.fileType !== "pdf" &&
      //   res.fileType !== "xlsx" &&
      //   res.fileType !== "xls" &&
      //res.fileType === 'doc' &&
      //   res.fileType === 'docx'
      // ) {
      //   this.$message.warning("只支持pdf与excel格式的文件预览");
      //   return;
      // }
      let typeList = {
        pdf: "application/pdf",
        xls: "application/vnd.ms-excel",
        xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        doc: "application/msword",
        docx: "application/msword",
      };
      const blob = new Blob([res], { type: typeList[fileType] });
      if (fileType === "pdf") {
        this.pdf = URL.createObjectURL(blob);
      } else if (fileType === "doc" || fileType === "docx") {
        doc.renderAsync(blob, document.querySelector("#tableHtml")); // 渲染到页面
      } else {
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = new Uint8Array(e.target.result);
          let workbook = XLSX.read(data, { type: "array" }); // 解析数据
          this.tableToHtml(workbook);
        };
        reader.readAsArrayBuffer(blob);
      }
      this.dialogPreVisible = true;
    },

    tableToHtml(workbook) {
      var worksheet = workbook.Sheets[workbook.SheetNames[0]];
      // var innerHTML = XLSX.utils.sheet_to_html(worksheet);
      if (document.querySelector("#tableHtml")) {
        document.querySelector("#tableHtml").innerHTML =
          XLSX.utils.sheet_to_html(worksheet);
        document.querySelector(".table-html-wrap table");
        let trs = document.querySelectorAll("tr");
        trs.forEach((tr) => {
          if (!tr.innerText.trim()) {
            tr.remove();
          }
        });
        document.querySelector(".el-dialog__body").style.overflowX = "auto";
      }
      let tds = document.querySelectorAll("td");
    },
    // 保存
    saveForm() {
      // 校验
      let flag = this.$refs["childRules"].validateForm();

      if (flag) {
        // 已有审核通过的试验方案
        if (this.addDialogVisibleTitle == "新增") {
          if (
            this.getFrom.reportIsAudited == 1 &&
            this.$refs.childRules.auditedFileList &&
            this.$refs.childRules.auditedFileList.length > 0
          ) {
            this.$confirm(
              "该次测试已有审核通过的试验方案，是否替换？",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            ).then(() => {
              this.insertOrUpdateStationInfoFile();
              this.dialogFormVisible = false;
            });
          } else {
            this.insertOrUpdateStationInfoFile();
            this.dialogFormVisible = false;
          }
        }
        if (this.addDialogVisibleTitle == "编辑") {
          this.updateStationFileWarn();
        }
      } else {
        return;
      }
    },

    // 首先封装参数（对象）转换为formData格式
    // getFormData(object) {
    //   const formData = new FormData();
    //   Object.keys(object).forEach((key) => {
    //     const value = object[key];
    //     if (Array.isArray(value)) {
    //       value.forEach((subValue, i) => {
    //         formData.append(key + `[${i}]`, subValue);
    //       });
    //     } else {
    //       formData.append(key, object[key]);
    //     }
    //   });
    //   return formData;
    // },

    // 首先封装参数（对象）转换为formData格式

    getFormData() {
      let form = this.$refs.childRules;
      // 文件存在就append,不存在就不append,不往后台传递这个字段
      // form.fileList1[0] &&
      //   this.formData.set("regulationReportForm", form.fileList1[0].raw);
      // form.fileList2[0] &&
      //   this.formData.set("regulationTestPlan", form.fileList2[0].raw);
      form.fileList2[0] &&
        this.formData.set("regulationTestReport", form.fileList2[0].raw);
      // form.fileList4[0] &&
      //   this.formData.set("responsePlan", form.fileList4[0].raw);
      // form.fileList5[0] &&
      //   this.formData.set("responseReport", form.fileList5[0].raw);
      // this.formData.set(
      //   "regulationTestPlanId",
      //   this.getFrom.regulationTestPlanId
      //     ? this.getFrom.regulationTestPlanId
      //     : null
      // );
      this.formData.set(
        "regulationOrgId",
        this.getFrom.regulationOrgId ? this.getFrom.regulationOrgId : null
      );
      this.formData.set(
        "stationName",
        this.getFrom.stationName ? this.getFrom.stationName : null
      );
      this.formData.set(
        "voltageLevelCode",
        this.getFrom.voltageLevelCode ? this.getFrom.voltageLevelCode : ""
      );
      this.getFrom.stationName &&
        this.formData.set("stationName", this.getFrom.stationName);
      this.formData.set("ownersName", this.getFrom.ownersName);
      this.formData.set("isProduction", this.getFrom.isProduction);
      this.formData.set("stationCap", this.getFrom.stationCap);
      this.formData.set("isRegulation", this.getFrom.isRegulation);
      this.formData.set("testDate", this.getFrom.testDate);
      this.formData.set("testNumber", this.getFrom.testNumber);
      this.formData.set("relationFileId", this.getFrom.relationFileId);
      this.formData.set("isTestPassed", this.getFrom.isTestPassed);
      if (
        this.getFrom.regulationTime === undefined ||
        this.getFrom.regulationTime === null
      ) {
        delete this.getFrom.regulationTime;
      } else {
        this.formData.set("regulationTime", this.getFrom.regulationTime);
      }
      //this.getFrom.regulationTime && this.formData.set('regulationTime', this.getFrom.regulationTime.replace('T', ' '))
      this.formData.set("unRegulateReason", this.getFrom.unRegulateReason);
      // 上调/下调是否投入
      this.formData.set(
        "adjustRegulationCode",
        this.getFrom.adjustRegulationCode
      );
      if (
        this.getFrom.isResponse === undefined ||
        this.getFrom.isResponse === null
      ) {
        delete this.getFrom.isResponse;
      } else {
        this.formData.set("isResponse", this.getFrom.isResponse);
      }

      this.getFrom.deadZone &&
        this.formData.set("deadZone", this.getFrom.deadZone);
      this.getFrom.adjustRatio &&
        this.formData.set("adjustRatio", this.getFrom.adjustRatio);
      this.getFrom.startingPowerThreshold &&
        this.formData.set(
          "startingPowerThreshold",
          this.getFrom.startingPowerThreshold
        );
      this.getFrom.lowerLimit &&
        this.formData.set("lowerLimit", this.getFrom.lowerLimit);
      this.getFrom.powerAdjustDeviation &&
        this.formData.set(
          "powerAdjustDeviation",
          this.getFrom.powerAdjustDeviation
        );
      this.getFrom.upLimit &&
        this.formData.set("upLimit", this.getFrom.upLimit);
      this.getFrom.startTime &&
        this.formData.set("startTime", this.getFrom.startTime);
      this.getFrom.responseTime &&
        this.formData.set("responseTime", this.getFrom.responseTime);
      this.getFrom.adjustTime &&
        this.formData.set("adjustTime", this.getFrom.adjustTime);
      // 一次调频投退功能
      this.getFrom.onOffFunction &&
        this.formData.set("onOffFunction", this.getFrom.onOffFunction);
      this.getFrom.isUpFunction &&
        this.formData.set("isUpFunction", this.getFrom.isUpFunction);
      this.getFrom.isLowerFunction &&
        this.formData.set("isLowerFunction", this.getFrom.isLowerFunction);
      this.getFrom.isResponseFunction &&
        this.formData.set(
          "isResponseFunction",
          this.getFrom.isResponseFunction
        );
      this.getFrom.agcControl &&
        this.formData.set("agcControl", this.getFrom.agcControl);
      this.getFrom.maxUpdownPower &&
        this.formData.set("maxUpdownPower", this.getFrom.maxUpdownPower);
      this.getFrom.adjustSpeed &&
        this.formData.set("adjustSpeed", this.getFrom.adjustSpeed);
      this.getFrom.maxUpdownPowerDuration &&
        this.formData.set(
          "maxUpdownPowerDuration",
          this.getFrom.maxUpdownPowerDuration
        );
      // 主动测试
      this.getFrom.activeTestNum &&
        this.formData.set("activeTestNum", this.getFrom.activeTestNum);
      this.getFrom.qualifiedNum &&
        this.formData.set("qualifiedNum", this.getFrom.qualifiedNum);
      this.getFrom.qualifiedRatio &&
        this.formData.set("qualifiedRatio", this.getFrom.qualifiedRatio);
      this.getFrom.caseIsAudited &&
        this.formData.set(
          "caseIsAudited",
          this.getFrom.caseIsAudited ? this.getFrom.caseIsAudited : ""
        );
      // this.getFrom.caseIsAudited &&
      //   this.formData.set("caseIsAudited", this.getFrom.caseIsAudited);
      this.getFrom.caseAuditTime &&
        this.formData.set("caseAuditTime", this.getFrom.caseAuditTime);
      this.getFrom.reportIsAudited &&
        this.formData.set("reportIsAudited", this.getFrom.reportIsAudited);
      this.getFrom.reportAuditTime &&
        this.formData.set("reportAuditTime", this.getFrom.reportAuditTime);

      //
      this.getFrom.testDate &&
        this.formData.set("testDate", this.getFrom.testDate); //测试日期
      this.getFrom.testNumber &&
        this.formData.set("testNumber", this.getFrom.testNumber); //测试序号
      this.getFrom.relationFileId &&
        this.formData.set("relationFileId", this.getFrom.relationFileId); //试验方案
      this.getFrom.isTestPassed &&
        this.formData.set("isTestPassed", this.getFrom.isTestPassed); //是否测试合格

      // 区分新增或者删除的时候传参
      if (this.operate === "add" || this.operate === "copy") {
        let queryInputList = form.queryInputList;

        let stationId = queryInputList.filter(
          (item) => item.label === form.detailForm.stationName
        )[0].value;

        this.formData.set("operateCode", "1");
        this.formData.set("stationType", "7");
        this.formData.set("stationId", stationId);

        if (
          this.getFrom.reportIsAudited == undefined ||
          this.getFrom.reportIsAudited == null ||
          this.getFrom.reportIsAudited == ""
        ) {
          this.formData.delete("reportIsAudited");
        }

        if (
          this.getFrom.reportAuditTime == undefined ||
          this.getFrom.reportAuditTime == null ||
          this.getFrom.reportAuditTime == ""
        ) {
          this.formData.delete("reportAuditTime");
        }

        if (
          this.getFrom.isTestPassed == undefined ||
          this.getFrom.isTestPassed == null
        ) {
          this.formData.delete("isTestPassed");
        }
      }

      if (this.operate === "edit") {
        let queryInputList = form.queryInputList;

        let stationId = queryInputList.filter(
          (item) => item.label === form.detailForm.stationName
        )[0].value;
        this.formData.set("operateCode", "2");
        this.formData.set("stationId", form.detailForm.stationId);
        //this.formData.set("regulationId", form.detailForm.regulationId);
        this.formData.set(
          "regulationTestReportId",
          this.getFrom.stationFileId ? this.getFrom.stationFileId : null
        );
        this.formData.set("stationType", "7");
        if (form.fileList2[0] == undefined) {
          this.formData.delete("regulationTestReport");
        }

        if (
          this.getFrom.reportIsAudited == undefined ||
          this.getFrom.reportIsAudited == null ||
          this.getFrom.reportIsAudited == ""
        ) {
          this.formData.delete("reportIsAudited");
        }

        if (
          this.getFrom.reportAuditTime == undefined ||
          this.getFrom.reportAuditTime == null ||
          this.getFrom.reportAuditTime == ""
        ) {
          this.formData.delete("reportAuditTime");
        }

        if (
          this.getFrom.isTestPassed == undefined ||
          this.getFrom.isTestPassed == null
        ) {
          this.formData.delete("isTestPassed");
        }
      }
      return this.formData;
    },

    // 新增
    async insertOrUpdateStationInfoFile() {
      this.formData = this.getFormData();
      this.formData.set("ownersId", this.$refs.childRules.$refs.owner.labels);
      this.formData.set("stationName", this.getFrom.stationName);
      this.formData.set("fileSort", "02");
      await insertStationInfoFile(this.formData).then((res) => {
        if (res.code === "000000") {
          Message.success(`${this.addDialogVisibleTitle}成功`);
          this.$refs.windPowerTable.getDataInit();
        }
      });
    },

    // 修改
    async updateStationInfoFile() {
      this.formData = this.getFormData();
      this.formData.set("ownersId", this.$refs.childRules.$refs.owner.labels);
      this.formData.set("stationName", this.getFrom.stationName);
      this.formData.set("fileSort", "02");
      await updateStationInfoFile(this.getFormData(this.formData)).then(
        (res) => {
          if (res.code === "000000") {
            Message.success(`${this.addDialogVisibleTitle}成功`);
            this.$refs.windPowerTable.getDataInit();
          }
        }
      );
    },

    // 编辑电厂文件-测试方案/结果  弹窗提醒
    async updateStationFileWarn() {
      this.formData = this.getFormData();
      this.formData.set("ownersId", this.$refs.childRules.$refs.owner.labels);
      this.formData.set("stationName", this.getFrom.stationName);
      this.formData.set("fileSort", "02");
      await updateStationFileWarn(this.getFormData(this.formData)).then(
        (res) => {
          if (res.code === "000000") {
            if (res.data == true) {
              this.updateStationInfoFile();
              this.dialogFormVisible = false;
            } else {
              this.$confirm(
                "该次测试已有审核通过的试验方案，是否替换？",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              ).then(() => {
                this.updateStationInfoFile();
                this.dialogFormVisible = false;
              });
            }
          }
        }
      );
    },

    //列表查看，跳转到新型资源快速频率响应主动测试页面
    doCheck() {
      this.$router.push({ path: "/windPower", query: { stationId: "001" } });
      // this.$router.push({ name: 'home', params: { id: '001' } })
    },

    // 最外部检索按钮
    searchOrder() {
      this.$nextTick(() => {
        this.$refs.windPowerTable.getDataInit();
      });
    },

    handleClear() {
      this.getTreeData();
    },
  },
};
